import os
import img2pdf
from PyPDF2 import PdfMerger

subfolders = []
cunt=0
# 构建包含旋转设置的参数选项
pdf_options = {
    "rotation": img2pdf.Rotation.ifvalid
}
def convert_image_to_pdf(image_path):
    """
    将单个图片文件转换为PDF文件
    """
    with open(image_path, "rb") as image_file:
        # tt=os.path.exists(image_path)
        try:
         pdf_bytes = img2pdf.convert(image_file,**pdf_options)
        except Exception as e:
            print("转换出错：", e)
    pdf_path = os.path.splitext(image_path)[0] + ".pdf"
    with open(pdf_path, "wb") as pdf_file:
        pdf_file.write(pdf_bytes)
        # pdf_file.close()
    return pdf_path


def merge_files_in_folders(folder_list, output_pdf_path):
    """
    合并多个文件夹下的文件到一个PDF文件中
    """
    merger = PdfMerger()
    ListTenmp = []
    for folder in folder_list:
        for root, dirs, files in os.walk(folder):
            for file in files:
                file_path = os.path.join(root, file)
                file_extension = os.path.splitext(file_path)[1].lower()
                if file_extension in [".jpg", ".jpeg", ".png", ".bmp", ".gif"]:
                    pdf_path = convert_image_to_pdf(file_path)
                    # os.remove(pdf_path)
                    merger.append(pdf_path)
                    ListTenmp.append(pdf_path)

                elif file_extension == ".pdf":
                    merger.append(file_path)
    with open(output_pdf_path, "wb") as output_file:
        merger.write(output_file)
    merger.close()
    for li in ListTenmp:
        os.remove(li)  # 删除临时生成的图片转的PDF文件（可选，可根据需求保留）
def get_subfolders_list(directory):
    for item in os.listdir(directory):
        item_path = os.path.join(directory, item)
        if os.path.isdir(item_path):
            subfolders.append(item_path)
    return subfolders

# 示例用法，指定多个文件夹列表和输出的PDF文件名
# folders = get_subfolders_list(r'D:\myself\savePDF\test\电子科大财务明细1130\报销凭证') # 替换为实际的文件夹路径列表
folders = get_subfolders_list(r'D:\myself\savePDF\test\电子科大财务明细1130\报销凭证') # 替换为实际的文件夹路径列表
output_path = "merged.pdf" # 输出的PDF文件名
if os.path.exists(output_path):
    os.remove(output_path)
merge_files_in_folders(folders, output_path)